package com.zjtx.tech.demo.controller;

import com.zjtx.tech.demo.entity.CameraInfo;
import com.zjtx.tech.demo.service.RedisGeoService;
import com.zjtx.tech.demo.utils.GeoPointGenerator;
import com.zjtx.tech.demo.utils.Result;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("camera")
public class RedisGeoDemoController {

    @Resource
    private RedisGeoService redisGeoService;

    public static final List<CameraInfo> CAMERA_INFO_LIST = new ArrayList<>();

    static {
        double centerLongitude = 116.3975;
        double centerLatitude = 39.9042;
        List<Double[]> geoPoints = GeoPointGenerator.generateGeoPoints(centerLongitude, centerLatitude);
        for (int i = 0; i < geoPoints.size(); i++) {
            CameraInfo cameraInfo = new CameraInfo();
            cameraInfo.setId(i);
            cameraInfo.setName("camera" + i);
            cameraInfo.setLongitude(geoPoints.get(i)[0]);
            cameraInfo.setLatitude(geoPoints.get(i)[1]);
            cameraInfo.setAddress("address" + i);
            CAMERA_INFO_LIST.add(cameraInfo);
        }
    }

    @GetMapping("list")
    public Result getCameraList(double longitude, double latitude) {
        CAMERA_INFO_LIST.forEach(cameraInfo -> {
            redisGeoService.addMember("cameras", cameraInfo.getName(), cameraInfo.getLongitude(), cameraInfo.getLatitude());
        });
        GeoResults<RedisGeoCommands.GeoLocation<String>> res = redisGeoService.radiusCondition("cameras", longitude, latitude, 1, 3);
        res.getContent().forEach(result -> System.out.println(result.getContent().getName()));
        return Result.ok(res);
    }

}
